//
//  BookShoppingWebViewController.m
//  QiYReader
//
//  Created by 奇阅科技 on 14/12/12.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "BookShoppingWebViewController.h"
#import "Book.h"
#import "ZMYBookInfoViewController.h"
#import "UIViewControllerAdditions.h"
#import "ZMYThemeCommentTableViewController.h"
#import "QYLoadingView.h"
#import "ThemeComment.h"
#import "UserAccount.h"
#import "TaskList.h"
#import "MobClick.h"
#define ReadPackage1 @"ReadPackage1"
#define ReadPackage2 @"ReadPackage2"
#define ReadPackage3 @"ReadPackage3"
#define ReadPackage4 @"ReadPackage4"
#define ReadPackage5 @"ReadPackage5"
#define ReadPackage6 @"ReadPackage6"
#import "AppDelegate.h"
#import <StoreKit/StoreKit.h>
#import <StoreKit/SKPaymentTransaction.h>
#import "RechargeRecord.h"
#import "ZMYNetWorkAPI.h"
#import "ZMYLKDB.h"
@interface BookShoppingWebViewController()<UIWebViewDelegate,SKProductsRequestDelegate, SKPaymentTransactionObserver>
{
    QYLoadingView *loadingView;
    __weak IBOutlet UIImageView *loadFailImageView;
    // 产品字典
    NSMutableDictionary *_productDict;
    BOOL isLoadingFinished;
    NSString *buyingProduct;
    NSString *productId;
    NSString *coin_num;
}

@end
@implementation BookShoppingWebViewController
-(void)viewDidLoad{
    [super viewDidLoad];
    
    [self setBarBackgroundImage:@"navBackground"];
    [self setTitleForNavigation:self.titleStr];
    [self setLeftBackButtonForNavigation];
    loadingView = [[[NSBundle mainBundle]loadNibNamed:@"QYLoadingView" owner:self options:nil] lastObject];
    UserAccount *user = [UserAccount currentAccount];
    if (user) {
        if ([self.urlStr rangeOfString:@"taskname=store"].location!=NSNotFound) {
            self.urlStr = [NSString stringWithFormat:@"%@&uid=%@&token=%@",self.urlStr,user.uid,user.token];
            TaskList *taskList = [TaskList currentAccount];
            Task *task = taskList.taskArray[1];
            if (!task.isFinshed) {
                task.isFinshed = YES;
                [TaskList saveAccount:taskList];
            }
        }
    }
    NSMutableURLRequest *reque = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
    reque.timeoutInterval = 10;
    self.webView.delegate = self;
    [self.webView loadRequest:reque];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.isPushByNav) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    } else {
        [self.navigationController setNavigationBarHidden:YES animated:NO];
    }
    
}
#pragma mark - THSegmentedPageViewControllerDelegate
- (NSString *)viewControllerTitle
{
    return self.titleStr;
}
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlString = [[request URL] absoluteString];
    urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
    if([urlComps count]==2 && [[urlComps objectAtIndex:0] isEqualToString:@"ios"])
    {
        NSArray *arrFucnameAndParameter = [(NSString*)[urlComps objectAtIndex:1] componentsSeparatedByString:@"/omituofo"];
        NSString *funcStr = [arrFucnameAndParameter objectAtIndex:0];
        if (arrFucnameAndParameter.count==1) {
            if ([funcStr hasPrefix:@"ReadPackage"]) {
                arrFucnameAndParameter = [funcStr componentsSeparatedByString:@":"];
                funcStr = [arrFucnameAndParameter objectAtIndex:0];
                coin_num = [arrFucnameAndParameter objectAtIndex:1];
                [MobClick event:@"2006" attributes:@{@"ReadPackage" : @"funcStr"} counter:[coin_num intValue]];
                //向服务器请求订单号
                __weak typeof(self) weakSelf = self;
                [[ZMYNetWorkAPI default]getProductIdReadPackage:funcStr Response:^(NSDictionary *resultDic) {
                    buyingProduct = funcStr;
                    productId = [resultDic objectForKey:@"trade_no"];
                    [[SKPaymentQueue defaultQueue] addTransactionObserver:weakSelf];
                    [self requestProducts];
                } error:^(NSString *errorStr) {
                    [AppDelegate showHUDAndHide:errorStr view:[AppDelegate delegate].window];
                    [loadingView closeView];
                }];
                return NO;
            }else if ([funcStr isEqualToString:@"login"]){
                [AppDelegate showHUDAndHide:@"请登录后继续操作" view:[AppDelegate delegate].window];
                return NO;
            }else if ([funcStr isEqualToString:@"getnull"]){
                [AppDelegate showHUDAndHide:@"信息获取失败" view:[AppDelegate delegate].window];
                return NO;
            }else if ([funcStr isEqualToString:@"nopay"]){
                [AppDelegate showHUDAndHide:@"没有需要支付的信息 " view:[AppDelegate delegate].window];
                return NO;
            }
        }
        if (arrFucnameAndParameter.count!=2) {
            return NO;
        }
        if ([funcStr isEqualToString:@"goBookDetail"]) {
            [self goBookDetail:[arrFucnameAndParameter objectAtIndex:1]];
        } else if ([funcStr isEqualToString:@"goReading"]) {
            [self goReading:[arrFucnameAndParameter objectAtIndex:1]];
        }else if ([funcStr isEqualToString:@"gotonextview"]) {
            [self goToNextView:[arrFucnameAndParameter objectAtIndex:1]];
        }else if ([funcStr isEqualToString:@"goBookcomment"]) {
            [self goToCommentListView:[arrFucnameAndParameter objectAtIndex:1]];
        }
        return NO;
    }
    if ([urlComps count]==2 && [[urlComps objectAtIndex:0] isEqualToString:@"http"]) {
        [loadingView showView];
    }
    return YES;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if (title.length>1) {
        [self setTitleForNavigation:title];
    }
    [loadingView closeView];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [loadingView closeView];
    self.webView.hidden = YES;
}
- (IBAction)reloadWebAgain:(id)sender {
    self.webView.hidden = NO;
    NSMutableURLRequest *reque = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
    reque.timeoutInterval = 10;
    [self.webView loadRequest:reque];
}
-(void)goBookDetail:(NSString*)articleid
{//书本详情
    NSArray *array = [articleid componentsSeparatedByString:@"/mamimamihong"];
    if (array.count!=2) {
        return;
    }
    Book *book = [Book new];
    book.articleid = array[0];
    book.title = array[1];
    book.imagefname = [NSString stringWithFormat:@"http://dataapi.yuewen.cc/web/images/coverpic/%@.jpg",array[0]];
    ZMYBookInfoViewController *view = [[UIStoryboard storyboardWithName:@"BookShop" bundle:nil]instantiateViewControllerWithIdentifier:@"ZMYBookInfoViewController"];
    view.book = book;
    [self.navigationController pushViewController:view animated:YES];
}
-(void)goReading:(NSString*)titleUrl
{
    //书城内部跳转
    NSArray *array = [titleUrl componentsSeparatedByString:@"/mamimamihong"];
    if (array.count!=2) {
        return;
    }
    BookShoppingWebViewController * childView = [self.storyboard instantiateViewControllerWithIdentifier:@"BookShoppingWebViewController"];
    childView.titleStr = array[0];
    childView.urlStr = [NSString stringWithFormat:@"http://dataapi.yuewen.cc%@",array[1]];
    childView.isPushByNav = YES;
    [self.navigationController pushViewController:childView animated:YES];
}
-(void)goToNextView:(NSString*)titleUrl
{
    //更多的跳转
    NSArray *array = [titleUrl componentsSeparatedByString:@"/mamimamihong"];
    if (array.count!=1) {
        return;
    }
    BookShoppingWebViewController * childView = [self.storyboard instantiateViewControllerWithIdentifier:@"BookShoppingWebViewController"];
    childView.titleStr = @"";
    childView.urlStr = [NSString stringWithFormat:@"http://dataapi.yuewen.cc%@",array[0]];
    childView.isPushByNav = YES;
    [self.navigationController pushViewController:childView animated:YES];
}
-(void)goToCommentListView:(NSString*)titleUrl
{
    //跳转到评论列表页
    NSArray *array = [titleUrl componentsSeparatedByString:@"/mamimamihong"];
    if (array.count!=2) {
        return;
    }
    ZMYThemeCommentTableViewController * childView = [[UIStoryboard storyboardWithName:@"BookShop" bundle:nil] instantiateViewControllerWithIdentifier:@"ZMYThemeCommentTableViewController"];
    ThemeComment *themeComment = [ThemeComment new];
    themeComment.articleid = array[0];
    themeComment.commentid = array[1];
    childView.themeComment = themeComment;
    [self.navigationController pushViewController:childView animated:YES];
}
#pragma mark 询问苹果的服务器能够销售哪些商品
- (void)requestProducts
{
    if (loadingView.superview == nil) {
        [loadingView showView];
    }
    // 能够销售的商品
    NSSet *set = [[NSSet alloc] initWithObjects:ReadPackage1, ReadPackage2, ReadPackage3, ReadPackage4, ReadPackage5, ReadPackage6, nil];
    
    // "异步"询问苹果能否销售
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
    
    request.delegate = self;
    
    // 启动请求
    [request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    if (_productDict == nil) {
        _productDict = [NSMutableDictionary dictionaryWithCapacity:response.products.count];
    }
    
    for (SKProduct *product in response.products) {
        // 激活了对应的销售操作按钮，相当于商店的商品上架允许销售
        NSLog(@"%@", product.productIdentifier);
        
        if ([product.productIdentifier isEqualToString:ReadPackage1]) {
        }
        
        if ([product.productIdentifier isEqualToString:ReadPackage2]) {
        }
        if ([product.productIdentifier isEqualToString:ReadPackage3]) {
        }
        if ([product.productIdentifier isEqualToString:ReadPackage4]) {
        }
        if ([product.productIdentifier isEqualToString:ReadPackage5]) {
        }
        if ([product.productIdentifier isEqualToString:ReadPackage6]) {
        }
        // 填充商品字典
        [_productDict setObject:product forKey:product.productIdentifier];
    }
    if (loadingView.superview == nil) {
        [loadingView showView];
    }
    [self buyProduct:_productDict[buyingProduct]];
}
#pragma mark - 用户决定购买商品
- (void)buyProduct:(SKProduct *)product
{
    // 要购买产品(店员给用户开了个小票)
    SKPayment *payment = [SKPayment paymentWithProduct:product];
    
    // 去收银台排队，准备购买(异步网络)
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}
#pragma mark - SKPaymentTransaction Observer
#pragma mark 购买队列状态变化
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    if (loadingView.superview == nil) {
        [loadingView showView];
    }
    // 调试
    for (SKPaymentTransaction *transaction in transactions) {
        NSLog(@"队列状态变化 %@", transaction.description);
        // 如果小票状态是购买完成
        if (SKPaymentTransactionStatePurchased == transaction.transactionState) {
            NSLog(@"购买完成 %@", transaction.payment.productIdentifier);
            // 更新界面或者数据，把用户购买得商品交给用户
            // ...
            // 验证购买凭据
            [self verifyPruchase:transaction];
            // 将交易从交易队列中删除
            [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
        } else if (SKPaymentTransactionStateFailed == transaction.transactionState) {
            NSLog(@"购买失败 %@", transaction.payment.productIdentifier);
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            [loadingView closeView];
            [AppDelegate showHUDAndHide:transaction.error.localizedDescription view:[AppDelegate delegate].window];
        } else if (SKPaymentTransactionStateRestored == transaction.transactionState) {
            NSLog(@"恢复成功 %@", transaction.payment.productIdentifier);
            // 更新界面或者数据，把用户购买得商品交给用户
            // ...
            // 将交易从交易队列中删除
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            [loadingView closeView];
            [AppDelegate showHUDAndHide:@"恢复成功" view:[AppDelegate delegate].window];
        }
    }
}
#pragma mark 验证购买凭据
- (void)verifyPruchase:(SKPaymentTransaction *)transaction
{
    // 验证凭据，获取到苹果返回的交易凭据
    // appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    // 从沙盒中获取到购买凭据
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    // 在网络中传输数据，大多情况下是传输的字符串而不是二进制数据
    // 传输的是BASE64编码的字符串
    //BASE64 常用的编码方案，通常用于数据传输，以及加密算法的基础算法，传输过程中能够保证数据传输的稳定性
    //BASE64是可以编码和解码的
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    if (encodeStr.length<10) {
        [loadingView closeView];
        [AppDelegate showHUDAndHide:@"充值失败！" view:[AppDelegate delegate].window];
        return;
    }
    [MobClick event:@"2007"];
    RechargeRecord *recharge = [RechargeRecord new];
    recharge.uid = [UserAccount currentAccount].uid;
    recharge.rechargeRecordID = productId;
    NSDictionary *moneyDict = @{ReadPackage1:@"6",ReadPackage2:@"30",ReadPackage3:@"50",ReadPackage4:@"98",ReadPackage5:@"198",ReadPackage6:@"588"};
    recharge.money = moneyDict[buyingProduct];
    recharge.coin_num = coin_num;
    recharge.receiptBASE64 = encodeStr;
    recharge.time = [NSString stringWithFormat:@"%.f",[ZMYNetWorkAPI currentTime]];
    [[ZMYLKDB getLKDBHelper] updateRechargeRecord:recharge];
    //向服务器发生票据
    [[ZMYNetWorkAPI default]updateYuebi:recharge Response:^(NSDictionary *resultDic) {
        [loadingView closeView];
        [AppDelegate showHUDAndHide:@"恭喜您充值成功！" view:[AppDelegate delegate].window];
    } error:^(NSString *errorStr) {
        [loadingView closeView];
        [AppDelegate showAlert:@"错误" message:@"服务器验证失败,请稍后在“我的”-“充值记录”里面选择账单进行恢复"];
    }];
    return;
}
@end
